package com.hltx.controller.login;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.hltx.controller.base.BaseController;
import com.hltx.pojo.smscode.SmsCodeValidate;
import com.hltx.pojo.user.User;
import com.hltx.pojo.user.UserLogin;
import com.hltx.service.smscode.impl.SmsCodeValidateService;
import com.hltx.service.user.UserManager;
import com.hltx.util.CustomUtil;
import com.hltx.util.DateUtil;
import com.hltx.util.MD5Util;
import com.hltx.util.MessagesCode;
import com.hltx.util.RegexUtils;
import com.hltx.util.ResultInfo;
import com.hltx.util.sms.code.NeteaseSms;

@Controller
public class UserLoginController extends BaseController {
	
	@Resource(name="userService")
	private UserManager userService;
	
	/*@Autowired
	private UserVipManager uservipService;*/
	
	@Resource(name ="smsCodeValidateService")
	private SmsCodeValidateService smsCodeValidateService;
	
	@RequestMapping( value = "toLogin")
	public ModelAndView toLogin(){
		ModelAndView view = this.getModelAndView();
		view.setViewName("user/login");
		return view;
	}
	
	@RequestMapping(value ="/login",method = { RequestMethod.POST})
	@ResponseBody
	public Map<String, Object> login(@ModelAttribute UserLogin userLogin,HttpServletResponse response,HttpServletRequest request){
		this.logBefore(logger, "用户登录");
		Map<String, Object> resMap = new HashMap<String, Object>();
			User result = null;
			User user = new User();
			String pwd = MD5Util.MD5(userLogin.getPwd());
				try {
					Integer is = userService.userIsExists(userLogin.getUserName());
					if (is > 0) {
						user.setUserName(userLogin.getUserName());
						user.setPwd(pwd);
						UserLogin u = userService.getUserMes(user);
						if(u != null){
							if(pwd.equals(u.getPwd())){
						userLogin.setPwd(pwd);
						UserLogin ul = userService.userLogin(userLogin);
						if(ul !=null){
							result = userService.getUserInfo(ul.getId());
							if(result !=null){
								request.getSession().setAttribute("sessionUser", result);
								resMap.put("user", result);
								resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", ""));
							}else{
								resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", "userIsNull"));
							}
						}else {
							resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", "userIsNull"));
						}
							}else{
								resMap.put("result",this.initResult(ResultInfo.ERROR, "err", "密码错误!"));
							}
						}else{
							resMap.put("result",this.initResult(ResultInfo.ERROR, "error", "用户不存在"));
						}
					}else{
						resMap.put("result",this.initResult(ResultInfo.ERROR, "error", "用户不存在"));
					}
				} catch (Exception e) {
					e.printStackTrace();
					this.logError(logger, e.getMessage());
					resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
				}
			this.logAfter(logger);
		
		return resMap;
	}
	
	@RequestMapping( value = "/toForgetpwd")
	public ModelAndView forgetpwd(){
		ModelAndView view = this.getModelAndView();
		view.setViewName("user/forgetpwd");
		return view;
	}
	
	@RequestMapping(value = "/toRegister")
	public ModelAndView toRegister(HttpServletRequest request){
		ModelAndView view = this.getModelAndView();
		String path = request.getContextPath(); 
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
		view.addObject("basePath", basePath);
		view.setViewName("user/register");
		return view;
	}
	
	@ResponseBody
	@RequestMapping(value ="/register")
	public Map<String, Object> register(HttpServletResponse response,HttpServletRequest request,@Param("code") String urlCode){
		this.logBefore(logger, "用户注册");
		Map<String, Object> resMap = new HashMap<String, Object>();
		String userName = request.getParameter("mobile");
		String pasword = request.getParameter("pasword");
		String hxId = "hltx"+MD5Util.MD5(userName);
		pasword = MD5Util.MD5(pasword);
		UserLogin login =new UserLogin();
		login.setPwd(pasword);
		login.setUserName(userName);
		login.setHxId(hxId);
		String msg = validateCocde(request);
		if ("ok".equals(msg)) {
			try {
				int i=userService.findByPhone(login);
				if(i<=0){
					int id = userService.saveUserRegister(login);
					if(id > 0){
						//环信注册
						/*try{
							userService.saveUserRegister1(login,id);
						}catch(Exception e){
							e.printStackTrace();
						}*/
						User resultUser = userService.getUserInfo(id);
						if(resultUser != null){
							request.getSession().setAttribute("sessionUser", resultUser);
							resMap.put("result", this.initResult(ResultInfo.SUCCESS, "ok", ""));
						}else{
							resMap.put("result", this.initResult(ResultInfo.ERROR, "error", "注册出现问题请及时联系"));
						}
					}else{
						resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
					}
				}else{
					resMap.put("result", this.initResult(ResultInfo.ERROR, "exist", MessagesCode.EXIST));
				}
			} catch (Exception e) {
				e.printStackTrace();
				this.logError(logger, e.getMessage());
				resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
			}
		}else if("expire".equals(msg)){
			resMap.put("result", this.initResult(ResultInfo.ERROR, "expire", MessagesCode.VALIDATE_EORROR));
		}else{
			 resMap.put("result", this.initResult(ResultInfo.ERROR, "error", MessagesCode.VALIDATE_EORROR));
		}
		this.logAfter(logger);
		return resMap;
	}
	@ResponseBody
	@RequestMapping("/send")
	public Map<String, Object> send(HttpServletResponse response,HttpServletRequest request){
		this.logBefore(logger, "发送短信验证码");
		Map<String, Object> resMap = new HashMap<String, Object>();
		String mobile = request.getParameter("userName");
		try{
			if(mobile != null){
				logBefore(logger, mobile);
				if(RegexUtils.isMobileNO(mobile)){
					//发送短信
					SmsCodeValidate sms = new SmsCodeValidate();
					sms.setPhone(mobile);
					
					String types =request.getParameter("type");
					sms.setTypes(types);
					SmsCodeValidate validate = smsCodeValidateService.getSmsData(sms);
					if (types != null) {
						Integer is = userService.userIsExists(mobile);
						if("register".equals(types)){
							 if(is > 0){
								 resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.HAVE, "此手机号已被注册"));
							 }else{
								 	if(validate ==null){
								 		sms.setExpireTime("120");
										String code =CustomUtil.buildRandom(6)+"";
										sms.setCode(code);
										sms.setSendNum(0);
										String msg = sendDB(sms, true);
										if (msg == "success") {
											resMap.put("result", this.initResult(ResultInfo.SUCCESS, code, "已发送短信"));
										}
								 	}else{
								 		sms.setExpireTime("120");
										String code =CustomUtil.buildRandom(6)+"";
										sms.setCode(code);
										sms.setSendNum(0);
										String msg = sendDB(sms, false);
										if (msg == "success") {
											resMap.put("result", this.initResult(ResultInfo.SUCCESS, code, "已发送短信"));
										}
								 	}
								 	
							 }
						}else{
							if(is<=0){
								resMap.put("result", this.initResult(ResultInfo.ERROR, "error", "此手机号不存在"));
							}else{
								if (validate ==null) {
									sms.setExpireTime("120");
									String code =CustomUtil.buildRandom(6)+"";
									sms.setCode(code);
									sms.setSendNum(0);
									String msg = sendDB(sms, true);
									if (msg == "success") {
										resMap.put("result", this.initResult(ResultInfo.SUCCESS, code, "已发送短信"));
									}
								}else{
									sms.setTypes(request.getParameter("type"));
									SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd"); 
									String date = format.format(new Date());
									String date_time= validate.getCreateTime();
									date_time = date_time.substring(0, 10).replace("-", "").trim();
									if(!date.equals(date_time)){
										validate.setSendNum(-1);
										smsCodeValidateService.intiSmsData(validate);
										sms.setExpireTime("120");
										String code =CustomUtil.buildRandom(6)+"";
										sms.setCode(code);
										sms.setSendNum(0);
										String msg = sendDB(sms, false);
										if (msg == "success") {
											resMap.put("result", this.initResult(ResultInfo.SUCCESS, code, "已发送短信"));
										}
									}else{
										if(validate.getSendNum()>=10){
											resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.ERROR, "获取验证码已经达到上线请在次日后再试"));
											//
										}else{
											long  now = System.currentTimeMillis();
											long  dates = Long.valueOf(DateUtil.dateToStamp(validate.getCreateTime())).longValue();
											if(validate != null && validate.getSendNum() < 3){
												sms.setExpireTime("120");
												String code =CustomUtil.buildRandom(6)+"";
												sms.setCode(code);
												sms.setSendNum(0);
												String msg = sendDB(sms, false);
												if (msg == "success") {
													resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, "已发送短信"));
												}
											}else{
												if(validate != null &&  validate.getSendNum() >= 3 && ((now/1000) - (dates/1000)) > 900){//发送次数大于3次并且上次生成验证码时间间隔大于15分钟
													sms.setExpireTime("120");
													String code =CustomUtil.buildRandom(6)+"";
													sms.setCode(code);
													sms.setSendNum(0);
													String msg = sendDB(sms, false);
													if (msg == "success") {
														resMap.put("result", this.initResult(ResultInfo.SUCCESS, code, "已发送短信"));
													}
												}else{
													resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.ERROR, "请求次数过于频繁请稍后再试"));
												}
											}
										}
										
									}
								}
								
							}
							
						}
					}else{
						resMap.put("result", this.initResult(ResultInfo.ERROR, "exception", "缺少类型参数"));
					}
				}else{
					resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.ERROR, "手机号码不合法!"));
				}
			}else{
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.HPONE_ISNULL, "手机号码不能为空!"));
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		this.logAfter(logger);
		return resMap;
	}
	
	@RequestMapping(value = "/outLogin")
	public ModelAndView outLogin(HttpServletResponse response,HttpServletRequest request){
		ModelAndView view  = this.getModelAndView();
		request.getSession().removeAttribute("sessionUser");
		view.setViewName("redirect:/toLogin");
		return view;
	}
	
	@ResponseBody
	@RequestMapping(value ="/updateNewPwd")
	public Map<String, Object>  updateNewPwd(HttpServletResponse response,HttpServletRequest request){
		this.logBefore(logger, "设置新密码");
		Map<String, Object> map = new HashMap<>();
		String mobile = request.getParameter("userName");
		String password = request.getParameter("password");
		password = MD5Util.MD5(password);
		if(mobile != null){
				UserLogin login = new UserLogin();
				login.setUserName(mobile);
				login.setPwd(password);
				try {
					userService.updateNewsPwd(login);
					map.put("mobile", mobile);
					map.put("next", "/toLogin");
					map.put("result", this.initResult(ResultInfo.SUCCESS, "ok", MessagesCode.SUCCESS));
				} catch (Exception e) {
					e.printStackTrace();
					this.logError(logger, e.getMessage());
					map.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
				}
		}else{
			map.put("result", this.initResult(ResultInfo.SUCCESS, "ok", MessagesCode.HPONE_ISNULL));
		}
		this.logAfter(logger);
		return map;
	}
	
	/**
	 * 验证验证码是否正确
	 * @param user
	 * @param response
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping( value = "/toNewsPwd")
	public Map<String, Object>  toNewsPwd(@ModelAttribute User user,HttpServletResponse response,HttpServletRequest request){
		this.logBefore(logger, "设置新密码");
		Map<String, Object> map = new HashMap<>();
		String mobile =request.getParameter("mobile");
		String msg = validateCocde(request);
		if ("ok".equals(msg)) {
			map.put("mobile", mobile);
			map.put("next", "/toNewsPwdPage?mobile="+mobile);
			map.put("result", this.initResult(ResultInfo.SUCCESS, "ok", MessagesCode.SUCCESS));
		}else if("expire".equals(msg)){
			map.put("result", this.initResult(ResultInfo.SUCCESS, "expire", MessagesCode.VALIDATE_EORROR));
		} else{
			map.put("result", this.initResult(ResultInfo.SUCCESS, "error", MessagesCode.VALIDATE_EORROR));
		}
		this.logAfter(logger);
		return map;
	}
	/**
	 * 去向设置新密码页面
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "toNewsPwdPage")
	public ModelAndView toNewsPwdPage(HttpServletResponse response,HttpServletRequest request){
		ModelAndView view = this.getModelAndView();
		view.addObject("mobile", request.getParameter("mobile"));
		view.setViewName("user/newpwd");
		return view;
		
	}
	
	@ResponseBody
	@RequestMapping(value = "/updateNewsPwd")
	public Map<String, Object> updatePwd(@ModelAttribute UserLogin login,HttpServletResponse response,HttpServletRequest request){
		this.logBefore(logger, "设置新密码");
		Map<String, Object> map = new HashMap<>();
		if(login != null) {
			try {
				String msg =validateCocde(request);
				if ("ok".equals(msg)) {
					map.put("next", "/toNewsPwd");
					map.put("result", this.initResult(ResultInfo.SUCCESS, "ok", MessagesCode.SUCCESS));
				}else{
					map.put("result", this.initResult(ResultInfo.SUCCESS, "ok", MessagesCode.VALIDATE_EORROR));
				}
			} catch (Exception e) {
				e.printStackTrace();
				this.logError(logger, e.getMessage());
				map.put("result", this.initResult(ResultInfo.ERROR, "exception", "系统异常"));
			}
		}
		this.logAfter(logger);
		return map;
	}
	
	/**
	 * @param request
	 * @return
	 */
	private String validateCocde(HttpServletRequest request) {
		String  msg = "ok";
		String phone = request.getParameter("mobile");
		String code = request.getParameter("code");
		String types = request.getParameter("type");
		SmsCodeValidate sms = new SmsCodeValidate();
		sms.setPhone(phone);
		sms.setCode(code);
		sms.setTypes(types);
		try {
			SmsCodeValidate validate = smsCodeValidateService.getSmsCode(sms);
			if(validate != null){
				if ("01".equals(validate.getIsUse())) {
					msg ="expire";
				}else{
					SmsCodeValidate scv = smsCodeValidateService.getSmsIsExpire(sms);
					if (scv == null) {
						msg ="expire";
					}
				}
				
			}else{
				msg = "error";
			}
			if(msg == "ok"){
				validate.setIsUse("01");
				validate.setCode(code);
				smsCodeValidateService.upudateIsSue(validate);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return msg;
	}
	
	
	private String  sendDB(SmsCodeValidate sms,Boolean o){
			try {
				int i=0;
				if (o) {
					sms.setIsUse("00");
					i= smsCodeValidateService.saveSmsCode(sms);
				}else{
					sms.setIsUse("00");
					i = smsCodeValidateService.updateSmsCode(sms);
				}
				if(i>=1){
					NeteaseSms.sendTemplateSms(sms.getPhone(), sms.getCode());
				}
				return "success";
			} catch (Exception e) {
				e.printStackTrace();
				this.logError(logger, e.getMessage());
				return "error";
			}
	}
	
}
